package com.xxh.blog.init;

import com.xxh.blog.dao.CategoryDao;
import com.xxh.blog.entity.Category;
import com.xxh.blog.entity.Essay;
import com.xxh.blog.service.essayService;
import com.xxh.blog.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class InitData implements CommandLineRunner, ServletContextAware {

    ServletContext servletContext;

    @Autowired
    CategoryDao categoryDao;

    @Resource
    essayService essayService;

    @Autowired
    RedisUtil redisUtil;


    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext=servletContext;
    }



    /**
     * 程序启动的时候初始化页面菜单,初始化一周内热点数据
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        //初始化热点文章
        essayService.initHotEssay();

        //获取缓存中的热点文章，并且展示到前台
        Set<String> strings = redisUtil.zReverseRange("week:rank", 0, 6);

        List<Essay> HotEssayList = new ArrayList<>();
        for(String eid:strings){
            String title = (String)redisUtil.hGet("rank:essay:" + eid, "essay:title");
            String count = (String)redisUtil.hGet("rank:essay:" + eid, "essay:ccount");
            String id = (String)redisUtil.hGet("rank:essay:" + eid, "essay:id");
            Essay essay = new Essay();
            essay.setId(Long.parseLong(id));
            essay.setCommentCount(Integer.parseInt(count));
            essay.setTitle(title);
            HotEssayList.add(essay);
        }
        System.out.println(HotEssayList);


        //获取数据库所有的分类
        List<Category> categories = categoryDao.selectList(null);
        servletContext.setAttribute("categories",categories);
        servletContext.setAttribute("hotList",HotEssayList);
    }

}
